package com.fingard.dsp.bank.directbank.psbc01;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.FtpSet;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.*;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;

public class PSBC01Base extends DirectBase implements ITcpClient {
	private static TransIDHelper idHelper = new TransIDHelper(1, 999);

	protected String getQryTransID() {
		Date tmpDateNow = new Date();
		return Format.DateTime12Year2Format.format(tmpDateNow) + idHelper.getNextIDStr();
	}

	protected String getCharset() {
		return getBankConfig().getCharset("GBK");
	}

	protected void writeCommonHeader(XmlTextWriter xmlWriter, PSBC01Header p_bankHeader) throws Exception {
		if (StringHelper.isNullOrEmpty(p_bankHeader.OpName)) {
			throw new Exception("未赋值OpName");
		}
		if (StringHelper.isNullOrEmpty(p_bankHeader.OpDate)) {
			throw new Exception("未赋值OpDate");
		}
		xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\"" + getCharset() + "\" ?>");
		xmlWriter.writeStartElement("root");
		xmlWriter.writeStartElement("Head");
		xmlWriter.writeElementString("OpName", p_bankHeader.OpName);
		xmlWriter.writeElementString("Outsys_Code", bankFront.corpNo);
		xmlWriter.writeElementString("merch_id", bankFront.org);
		xmlWriter.writeElementString("OpDate", p_bankHeader.OpDate);
		xmlWriter.writeEndElement();
	}

	protected String[] sendToBank(String p_reqStr) throws Exception {
		String[] retStr = new String[] { "", "" };

		WriteBankLogLn("2.提交银行的地址：" + bankFront.serverIP + ":" + bankFront.serverPort);
		TcpPortClient tmpClient = new TcpPortClient(bankFront.serverIP, Integer.parseInt(bankFront.serverPort), this);
		int tmpReqBodyLen = p_reqStr.getBytes(getCharset()).length;
		String tmpReqHeader = String.format("%5s", tmpReqBodyLen).replace(' ', '0') + "00000";
		p_reqStr = tmpReqHeader + p_reqStr;

		String tmpCharset = getCharset();
		byte[] tmpBytesBody = p_reqStr.getBytes(tmpCharset);

		WriteBankLogStep2(p_reqStr);
		TcpReceiver tmpReceiver = tmpClient.sendMessage(tmpBytesBody);
		retStr[0] = tmpReceiver.connState;
		if (tmpReceiver.recBytes != null) {
			String tmpStrRet = new String(tmpReceiver.recBytes, 0, tmpReceiver.readedLength, tmpCharset);
			WriteBankLogStep3(tmpStrRet);
			if (tmpStrRet.contains("<")) {
				retStr[1] = tmpStrRet.substring(tmpStrRet.indexOf('<'));
			}
		} else {
			retStr[1] = tmpReceiver.getConnMsg();
		}
		if (!tmpReceiver.isCompleted) {
			WriteBankLogLn(tmpReceiver.getConnMsg());
		}
		return retStr;
	}

	protected FtpReceiver fileUpload(String filePath, String fileName) throws Exception {
		FtpSet ftpSet = bankFront.getFtpSet("ftpserver");
		FtpReceiver ftpReceiver = null;
		FtpPortClient ftpPortClient = null;
		try {
			String fullFilePath = filePath + File.separator + fileName;
			ftpPortClient = new FtpPortClient(ftpSet);
			WriteBankLogLn("本地文件路径:" + fullFilePath);
			WriteBankLogLn("FTP服务器文件路径:" + ftpSet.upDir);
			WriteBankLogLn2("FTP服务器文件上传地址:" + ftpSet.serverIP + ":" + ftpSet.port);

			ftpReceiver = ftpPortClient.uploadFile(fullFilePath, fileName);
		} catch (Exception e) {
			if (ftpPortClient != null) {
				try {
					ftpPortClient.disconnect();
				} catch (IOException ie) {
					e.printStackTrace();
					WriteBankLogLn(ie);
				}
			}
		}
		return ftpReceiver;
	}

	protected FtpReceiver fileDownload(String filename, Date transDate) throws Exception {
		FtpSet ftpSet = bankFront.getFtpSet("ftpserver");
		FtpReceiver ftpReceiver = null;
		FtpPortClient ftpPortClient = null;
		try {
			String localPath = getDataFileDirectory(transDate) + File.separator + "BatPayRecResult" + File.separator + filename;
			ftpPortClient = new FtpPortClient(ftpSet);
			WriteBankLogLn("FTP服务器下载文件:" + ftpSet.downDir + File.separator + filename);
			WriteBankLogLn2("FTP服务器文件下载地址:" + ftpSet.serverIP + ":" + ftpSet.port);
			ftpReceiver = ftpPortClient.downloadFile(filename, localPath);
			if (ftpReceiver.isCompleted) {
				WriteBankLogLn2("成功保存文件至本地:" + localPath);
			}
		} catch (Exception e) {
			if (ftpPortClient != null) {
				try {
					ftpPortClient.disconnect();
				} catch (IOException ie) {
					e.printStackTrace();
					WriteBankLogLn(ie);
				}
			}
		}
		return ftpReceiver;
	}

	public void getContentLength(TcpReceiver p_receiver) throws Exception {
		if (p_receiver.contentLength == -1) {
			String tmpCharset = getCharset();
			String tmpRecNow = new String(p_receiver.recBytes, 0, p_receiver.readedLength, tmpCharset);
			if (tmpRecNow.indexOf("</root>") >= 0) {
				p_receiver.contentLength = p_receiver.readedLength;
				p_receiver.contentStartIndex = 0;
			}
		}
	}

    // 上送格式为json格式
    protected String[] sendToATS(String jsonData) throws Exception {
        String[] retStr = new String[] { "", "" };
        WriteBankLogLn("2.提交ATS的地址：" + FGBiz.dspCenter.dspSet.receiptPushServerUrl);

        // 发送银行前置
        WebRequest tmpRequest = new WebRequest(FGBiz.dspCenter.dspSet.receiptPushServerUrl);
        tmpRequest.setConnectTimeout(10000);
        tmpRequest.setRequestProperty("connection", "Close");
        tmpRequest.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        String charsetName = getCharset();
        StringBuilder data = new StringBuilder();
        data.append(jsonData);
        WriteBankLogLn("3.推送给ATS的数据" + data.toString());
        byte[] tmpWriteBytes = data.toString().getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogLn("4.返回的数据" + retStr[1]);

        return retStr;
    }
}
